const path = require("node:path");
const fs = require("node:fs");
const {
    get_file_list,
    read_cfg,
    write_with_type,
    get_fst_file,
} = require("../utils/file_tool");
const { BaseCommand } = require("./base");

class MergeFilesCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const src_files = get_file_list(data.src);
        if (!fs.existsSync(data.dst) || !fs.lstatSync(data.dst).isDirectory()) {
            fs.mkdirSync(data.dst, {
                recursive: true,
            });
        }
        for (let i = 0; i < src_files.length; i++) {
            const src_file = src_files[i];
            const src_data = await read_cfg(src_file);
            let dst_data;
            const dst_file = path.join(
                get_fst_file(data.dst),
                path.relative(get_fst_file(data.base), src_file),
            );
            if (fs.existsSync(dst_file)) {
                dst_data = await read_cfg(dst_file);
            } else {
                dst_data = {};
            }
            for (const k in src_data) {
                dst_data[k] = src_data[k];
            }
            await write_with_type(dst_data, dst_file, undefined, data.options);
        }
    }
}

module.exports = {
    MergeFilesCommand,
};
